package com.huawei.cloudapp.model.management;

import static com.huawei.cloudapp.utils.CasCommonUtils.getManagementUrl;
import static com.huawei.cloudapp.utils.CasConstantsUtil.ERROR_CODE;
import static com.huawei.cloudapp.utils.CasConstantsUtil.LIST;
import static com.huawei.cloudapp.utils.CasConstantsUtil.PHONE;
import static com.huawei.cloudapp.utils.CasConstantsUtil.PHONE_ID;
import static com.huawei.cloudapp.utils.CasConstantsUtil.PHONE_NAME;
import static com.huawei.cloudapp.utils.CasConstantsUtil.REGION_ID;
import static com.huawei.cloudapp.utils.CasConstantsUtil.SESSION_ID;
import static com.huawei.cloudapp.utils.CasConstantsUtil.TOKEN;

import android.util.Log;

import androidx.annotation.NonNull;

import com.huawei.cloudapp.model.IPhoneModel;
import com.huawei.cloudapp.model.OnRequestListener;
import com.huawei.cloudapp.model.bean.CustomException;
import com.huawei.cloudapp.model.bean.PhoneInfo;
import com.huawei.cloudapp.model.bean.User;
import com.huawei.cloudapp.model.bean.direct.PhoneDetail;
import com.huawei.cloudapp.model.bean.direct.PhoneJobResponse;
import com.huawei.cloudapp.utils.CasCommonUtils;
import com.huawei.cloudapp.utils.CasConstantsUtil;
import com.huawei.cloudapp.utils.CasHttpUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class PhoneModel implements IPhoneModel {
    private static final String TAG = "PhoneModel";

    @Override
    public void getPhoneList(User user, HashMap<String, String> condition, String region, String projectId, int offset, int limit, OnRequestListener<PhoneInfo> onRequestListener) {
        String url = getManagementUrl() + "/" + PHONE + "/" + LIST;
        HashMap<String, String> requestHeader = new HashMap<String, String>();
        requestHeader.put(TOKEN, user.getUserTokenByRegion(region));
        requestHeader.put(SESSION_ID, user.getUserSessionId());
        CasHttpUtils.post(url, requestHeader, "", new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                onRequestListener.onFailure(e);
            }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) {
                try {
                    List<PhoneInfo> phoneInfos = parseResponseToPhoneList(response);
                    onRequestListener.onSuccess(phoneInfos, phoneInfos.size());
                } catch (Exception e) {
                    onRequestListener.onFailure(e);
                }
            }
        });
    }

    @Override
    public void getPhoneDetailInfo(User user, String region, String projectId, String phoneId, OnRequestListener<PhoneDetail> onRequestListener) {

    }

    @Override
    public void resetPhone(User user,
                           String region,
                           String projectId,
                           List<String> phoneIdList,
                           String imageId,
                           List<HashMap<String, String>> property,
                           OnRequestListener<PhoneJobResponse> onRequestListener) {

    }

    @Override
    public void restartPhone(User user,
                             String region,
                             String projectId,
                             List<String> phoneIdList,
                             String imageId,
                             List<HashMap<String, String>> property,
                             OnRequestListener<PhoneJobResponse> onRequestListener) {

    }

    public List<PhoneInfo> parseResponseToPhoneList(Response response) throws Exception {
        if (response == null) {
            Log.e(TAG, "Failed to get response from server.");
            throw new CustomException.EmptyResponseFromServerException();
        }


        String rspStr = response.body().string();
        if (rspStr == null) {
            Log.e(TAG, "Failed to get response from server.");
            throw new CustomException.EmptyResponseFromServerException();
        }

        //处理结果
        List<Map<String, String>> responseList = CasCommonUtils.parseJsonListMessage(rspStr);
        if (responseList.isEmpty()) {
            Map<String, Object> errorRsp = CasCommonUtils.parseJsonMessage(rspStr);
            if (errorRsp.containsKey(ERROR_CODE)) {
                if (errorRsp.get(ERROR_CODE).equals("CPH.MANAGER.USER.00003")) {
                    throw new CustomException.LogInInfoInvalidException();
                }
            } else {
                Log.e(TAG, "handleGetPhoneListResponse: failed to parse response json str, " + errorRsp.toString());
                throw new CustomException.FailedToGetPhoneListException();
            }
        }

        List<PhoneInfo> phoneInfoList = new ArrayList<>();
        for (Map<String, String> phoneInfo : responseList) {
            if (!phoneInfo.containsKey(PHONE_ID) || !phoneInfo.containsKey(PHONE_NAME)) {
                Log.e(TAG, "handleGetPhoneListResponse: failed to parse response json str ");
                throw new CustomException.FailedToGetPhoneListException();
            }
            phoneInfoList.add(new PhoneInfo(phoneInfo.get(PHONE_NAME), "8U-16G-1080P",
                    phoneInfo.get(PHONE_ID), CasConstantsUtil.REGION_INFO.get(phoneInfo.get(REGION_ID))));
        }
        return phoneInfoList;
    }
}
